package cn.josh.action;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.josh.bean.Ec_order;
import cn.josh.bean.Ec_shopcar;
import cn.josh.service.Ec_orderService;
import cn.josh.service.Ec_shopcarService;
import cn.josh.servicelmpl.Ec_orderServiceImpl;
import cn.josh.servicelmpl.Ec_shopcarServiceImpl;
import cn.josh.utill.MakeDate;
import cn.josh.utill.OrderCode;

@WebServlet("/OrderSubmitServlet")
public class OrderSubmitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		//得到session对象
		HttpSession session = request.getSession();

		
		//得到用户id
		String userId = (String)session.getAttribute("userId");
		
		//取得订单编号
		String orderCode = OrderCode.getOrderCode();
		
		//取得时间
		String createDate = MakeDate.makeDate();
		
		//取得商品总价格
		String amount = (String)request.getParameter("amount");
		
		//读取前端传入的商品id 并制成数组
		String [] articleIds = request.getParameterValues("checkbox");
		if(articleIds == null)
		{
			response.getWriter().append("<script>alert('请选择商品!');window.location.href='/ShoppingWebsite/ArticleCarReadServlet'</script>");
			return;
		}
		
		//将数据封装
		Ec_order order = new Ec_order();
		order.setOrderCode(orderCode);
		order.setCreateDate(createDate);
		order.setStatus("未签收");
		order.setAmount(amount);
		order.setUserId(userId);
		System.out.println(order);
		
		//调用数据库服务
		//添加订单
		Ec_orderService ecOrder = new Ec_orderServiceImpl();
		ecOrder.insertOrder(order);
		
		for(String articleId : articleIds)
		{
			//删除选择的商品
			Ec_shopcar shopcar = new Ec_shopcar();
			shopcar.setArticleId(articleId);
			shopcar.setUserId(userId);
			
			//调用数据库服务
			Ec_shopcarService ec_ser = new Ec_shopcarServiceImpl();
			ec_ser.deleteShop(shopcar);
		}
		
		response.sendRedirect("/ShoppingWebsite/OrderReadServlet");
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
